<script lang="ts" setup>
import { getPatientOrderAddressAPI } from '@/apis/address'
import { postPatientConsultPayAPI } from '@/apis/consult'
import { getPatientMedicineOrderPreAPI, postPatientMedicineOrderAPI } from '@/apis/medicine'
import type { AddressItem } from '@/types/address'
import type { CustomPaymentInstance } from '@/types/global-components'
import type { MedicineOrderPre } from '@/types/medicine'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 1. 获取收货地址
const addressInfo = ref<AddressItem>()
const getPatientOrderAddress = async () => {
  const res = await getPatientOrderAddressAPI()
  addressInfo.value = res.data.find((item) => item.isDefault === 1)
}
getPatientOrderAddress()

// 2. 获取预支付订单信息
// 页面加载时获取处方ID并请求数据
const props = defineProps<{
  id: string
}>()
const orderPre = ref<MedicineOrderPre>()
const getPatientMedicineOrderPre = async () => {
  if (!props.id) return
  const res = await getPatientMedicineOrderPreAPI(props.id)
  orderPre.value = res.data
}
getPatientMedicineOrderPre()

// 3. 立即支付
const customPaymentRef = ref<CustomPaymentInstance>()
const orderId = ref('')
// 点击立即支付按钮
const handlePay = async () => {
  if (!addressInfo.value?.id) {
    return uni.showToast({
      title: '请选择收货地址',
      icon: 'none',
    })  
  }
  // 如果订单ID不存在，则创建订单
  if (!orderId.value) {
    const res = await postPatientMedicineOrderAPI({
      id: props.id,
      addressId: addressInfo.value?.id,
      couponId: orderPre.value?.couponId,
    })
        // 保存订单ID
    orderId.value = res.data.id
  }
  // 打开支付组件
  customPaymentRef.value?.open()
}

const handleClose = async () => {
  // 二次确认提示
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得药品，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  // 如果用户选择关闭，则关闭支付弹窗
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}

// 确认支付
const handleConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({ title: '微信支付暂不支持', icon: 'none' })
  } else if (index === 1) {
    // #ifndef MP-WEIXIN
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback: 'http://localhost:5173/#/subpkg_medicine/pages/pay_result/pay_result',
    })
    location.href = res.data.payUrl
    // #endif
  }
}
</script>

<template>
  <scroll-view background-color="#f6f6f6">
    <view class="medicine-page">
      <view class="page-header">
        <view class="order-shippment">
          <view class="region">
            <uni-icons size="16" color="#FF7702" type="location-filled" />
            {{ addressInfo?.province }} {{ addressInfo?.city }} {{ addressInfo?.county }}
          </view>
          <view class="detail">{{ addressInfo?.addressDetail }}</view>
          <view class="receiver">
            {{ addressInfo?.receiver }}
            {{ addressInfo?.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') }}
          </view>
        </view>
      </view>

      <view class="order-shop">
        优医药房
        <text class="alt">优医质保 假一赔十</text>
      </view>
      <!-- 药品列表 -->
      <view class="medicine-list">
        <view class="medicine-list-item" v-for="item in orderPre?.medicines" :key="item.id">
          <image class="medicine-cover" :src="item.avatar" mode="aspectFill" />
          <view class="medicine-info">
            <text class="name">{{ item.name }}</text>
            <text class="unit symbol">{{ item.specs }}</text>
            <text class="price">¥{{ item.amount }}</text>
          </view>
          <view class="quantity">x{{ item.quantity }}</view>
          <view class="guide">用法用量：{{ item.usageDosag }}</view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-info">
        <uni-list :border="false">
          <uni-list-item title="药品金额" :right-text="`¥${orderPre?.payment || '0.00'}`" />
          <uni-list-item title="运费" :right-text="`¥${orderPre?.expressFee || '0.00'}`" />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPre?.couponDeduction || '0.00'}`"
          />
          <uni-list-item title="积分抵扣" :right-text="`-¥${orderPre?.pointDeduction || '0.00'}`" />
          <uni-list-item title="实付款" :right-text="`¥${orderPre?.actualPayment || '0.00'}`" />
        </uni-list>
      </view>

      <!-- 底部 -->
      <view class="toolbar">
        <view class="total-amount">
          需付款: <text class="number">¥{{ orderPre?.actualPayment || '0.00' }}</text>
        </view>
        <view class="buttons">
          <button class="uni-button" @click="handlePay">立即支付</button>
        </view>
      </view>
    </view>
    <!-- 自定义支付组件 -->
    <custom-payment
      ref="customPaymentRef"
      v-if="orderPre"
      :order-id="props.id"
      :amount="orderPre?.actualPayment"
      @close="handleClose"
    />
  </scroll-view>
</template>

<style lang="scss">
  @import './index.scss';
</style>